package com.ysxsoft.wdg.ui.activity.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.widget.TimeCount;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.REGISTER_OK;

public class RegisterActivity extends BaseActivity {

    public static void start(Context context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.et_invite)
    EditText etInvite;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.btn_code)
    TextView btnCode;
    @BindView(R.id.et_psw)
    EditText etPsw;

    private TimeCount timeCount;
    private String code = "", mobile = "", invicode = "", province = "", city = "", county = "", password = "";


    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("注册");
        timeCount = new TimeCount(60000, 1000, btnCode);

        initLocation();
    }

    @Override
    protected void setListener() {

    }

    @OnClick({R.id.title_finish, R.id.btn_code, R.id.btn_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.btn_code:
                mobile = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.showToast("请输入手机号");
                    return;
                }
                if (mobile.length()!=11) {
                ToastUtils.showToast("手机号码格式不正确");
                return;
            }
                postCode();
                break;
            case R.id.btn_register:
                mobile = etPhone.getText().toString().trim();
                password = etPsw.getText().toString().trim();
                invicode = etInvite.getText().toString().trim();
                code = etCode.getText().toString().trim();

                if (TextUtils.isEmpty(code) || TextUtils.isEmpty(mobile) || TextUtils.isEmpty(password) || TextUtils.isEmpty(invicode)) {
                    ToastUtils.showToast("输入信息不能为空...");
                    return;
                }

                postRegister();
                break;
        }
    }

    private void postRegister() {
        mApiHelper.postRegister(mobile, code, invicode, password, province, city, county, new Observer<BaseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean baseBean) {
                ToastUtils.showToast(baseBean.getMs());
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    EventBus.getDefault().post(new CommentEvent(REGISTER_OK,mobile));
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void postCode() {
        timeCount.start();
        mApiHelper.getMsmCode(mobile, new Observer<BaseBean<String>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBean<String> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    code = baseBean.getData();
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        ViewUtils.closeKeyboard(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    province = amapLocation.getProvince();
                    city = amapLocation.getCity();
                    county = amapLocation.getDistrict();
                    KLog.e("省--"+province+",市--"+city+",区--"+county);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    KLog.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };
    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);


        new RxPermissions(this)
                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) {
                        //启动定位
                        mLocationClient.startLocation();
                    }
                });
    }

}
